package cn.wildfire.chat.kit.contact.newfriend;

import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.sourcemuch.im.caiba.R;import com.sourcemuch.im.caiba.R2;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.wildfire.chat.app.extendsion.widgets.DispenseRecyclerView;
import cn.wildfire.chat.kit.WfcUIKit;
import cn.wildfire.chat.kit.contact.ContactViewModel;
import cn.wildfire.chat.kit.user.UserViewModel;
import cn.wildfirechat.model.FriendRequest;
import cn.wildfirechat.model.UserInfo;

public class FriendRequestViewHolder extends RecyclerView.ViewHolder {
    private FriendRequestListFragment fragment;
    private FriendRequestListAdapter adapter;
    private FriendRequest friendRequest;
    private UserViewModel userViewModel;
    private ContactViewModel contactViewModel;

    @BindView(R2.id.portraitImageView)
    ImageView portraitImageView;
    @BindView(R2.id.nameTextView)
    TextView nameTextView;
    @BindView(R2.id.introTextView)
    TextView introTextView;
    @BindView(R2.id.refuseButton)
    Button refuseButton;
    @BindView(R2.id.acceptButton)
    Button acceptButton;
    @BindView(R2.id.acceptStatusTextView)
    TextView acceptStatusTextView;
    @BindView(R2.id.ll_refuse)
    LinearLayout llRefuse;
    @BindView(R2.id.ll_delete)
    LinearLayout llDelete;

    public FriendRequestViewHolder(FriendRequestListFragment fragment, FriendRequestListAdapter adapter, View itemView) {
        super(itemView);
        this.fragment = fragment;
        this.adapter = adapter;
        ButterKnife.bind(this, itemView);
        userViewModel = WfcUIKit.getAppScopeViewModel(UserViewModel.class);
        contactViewModel = ViewModelProviders.of(fragment).get(ContactViewModel.class);
        /**
         * modify by HEKE , 2019/9/8 16:42 TODO 重写子控件的操作事件
         */
        this.maxSlidePxValue = itemView.getContext().getResources().getDimensionPixelSize(R.dimen.y150);
        this.itemView.setLongClickable(true);
        this.itemView.setOnTouchListener(onTouchListener);

        this.llRefuse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setClickRefuse();
            }
        });

        llDelete.setVisibility(View.GONE);
        this.llDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
    }

    public void setClickRefuse() {
        contactViewModel.refuseFriendRequest(friendRequest.target, friendRequest.fromsource).observe(fragment, aBoolean -> {
            if (aBoolean) {
                friendRequest.status = 2;
                setRefuse();
                DispenseRecyclerView dispenseRecyclerView = ((DispenseRecyclerView) itemView.getParent());
                dispenseRecyclerView.setFroceAllowSlidAnimation(true);
                dispenseRecyclerView.forceResetSlideValue();
            } else {
                Toast.makeText(fragment.getActivity(), "操作失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 触摸相关操作
     */
    private int downX;
    private long downTime;
    private final int slidegap = 12;
    private boolean haveMoved;
    private int slideTotal;
    private int maxSlidePxValue;

    /**
     * 隐藏其他选项
     *
     * @param parentView
     */
    private void wideOtherItem(RecyclerView parentView) {
        if (parentView == null) {
            return;
        }
        try {
            RecyclerView recyclerView = parentView;
            for (int i = 0; i < recyclerView.getChildCount(); i++) {
                View view1 = recyclerView.getChildAt(i);
                if (!view1.equals(itemView)) {
                    FriendRequestViewHolder childViewHolder = (FriendRequestViewHolder) view1.getTag();
                    if (childViewHolder != null) {
                        childViewHolder.slideTotal = 0;
                        childViewHolder.slideItemView(0);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * modify by HEKE , 2019/9/8 14:57 TODO 重新定义子控件的触摸事件
     */
    public View.OnTouchListener onTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent event) {
            try {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        downX = (int) event.getRawX();
                        downTime = System.currentTimeMillis();
                        haveMoved = false;
                        if (fragment != null) {
                            fragment.getAdapter().setFriendRequestViewHolder(FriendRequestViewHolder.this);
                            wideOtherItem(fragment.getRecyclerView());
                        }
                        return true;
                    case MotionEvent.ACTION_MOVE:
                        int moveX = (int) event.getRawX();
                        int poorX = downX - moveX;
                        int absPoorX = Math.abs(poorX);
                        if (absPoorX >= slidegap) {
                            haveMoved = true;
                        }
                        slideItemView((int) (poorX * 1.3f));
                        downX = moveX;
                        break;
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL:
                        // 单击进入子项对话
                        if (!haveMoved) {
                            long upTime = System.currentTimeMillis();
                            if ((upTime - downTime) <= 350) {
                            }
                        }
                        break;
                    default:
                        break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return true;
        }
    };

    @OnClick(R2.id.acceptButton)
    void accept() {
        contactViewModel.acceptFriendRequest(friendRequest.target, friendRequest.fromsource).observe(fragment, aBoolean -> {
            if (aBoolean) {
                friendRequest.status = 1;
                setAccept();
            } else {
                Toast.makeText(fragment.getActivity(), "操作失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @OnClick(R2.id.refuseButton)
    void refuse() {
        contactViewModel.refuseFriendRequest(friendRequest.target, friendRequest.fromsource).observe(fragment, aBoolean -> {
            if (aBoolean) {
                friendRequest.status = 2;
                setRefuse();
            } else {
                Toast.makeText(fragment.getActivity(), "操作失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void onBind(FriendRequest friendRequest) {
        this.friendRequest = friendRequest;
        UserInfo userInfo = userViewModel.getUserInfo(friendRequest.target, false);

        if (userInfo != null && !TextUtils.isEmpty(userInfo.displayName)) {
            nameTextView.setText(userInfo.displayName);
        } else {
            nameTextView.setText("<" + friendRequest.target + ">");
        }
        if (!TextUtils.isEmpty(friendRequest.reason)) {
            introTextView.setText(friendRequest.reason);
        }
        // TODO status

        switch (friendRequest.status) {
            case 0:
                acceptButton.setVisibility(View.VISIBLE);
                refuseButton.setVisibility(View.GONE);
                acceptStatusTextView.setVisibility(View.GONE);
                break;
            case 1:
                setAccept();
                break;
            case 2:
                setRefuse();
                break;
            default:
                break;
        }

        if (userInfo != null) {
            Glide.with(fragment).load(userInfo.portrait).apply(new RequestOptions().placeholder(R.mipmap.avatar_def).centerCrop()).into(portraitImageView);
        }
    }

    private void setAccept() {
        acceptButton.setVisibility(View.GONE);
        refuseButton.setVisibility(View.GONE);
        llDelete.setVisibility(View.GONE);
        acceptStatusTextView.setVisibility(View.VISIBLE);
        acceptStatusTextView.setText(fragment.getActivity().getString(R.string.had_added));
        this.maxSlidePxValue = 0;
    }

    private void setRefuse() {
        acceptButton.setVisibility(View.GONE);
        refuseButton.setVisibility(View.GONE);
        llDelete.setVisibility(View.GONE);
        acceptStatusTextView.setVisibility(View.VISIBLE);
        acceptStatusTextView.setText(fragment.getActivity().getString(R.string.had_refuse));
        this.maxSlidePxValue = 0;
    }

    /**
     * 滑动子控件
     *
     * @param poorX
     */
    private void slideItemView(int poorX) {
        try {
            slideTotal += poorX;
            if (slideTotal <= 0) {
                slideTotal = 0;
            } else if (slideTotal >= maxSlidePxValue) {
                slideTotal = maxSlidePxValue;
            }
            itemView.setScrollX(slideTotal);
            itemView.setFocusable(true);
            itemView.setFocusableInTouchMode(true);
            itemView.requestFocus();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public FriendRequest getFriendRequest() {
        return friendRequest;
    }

}
